package com.ht.aems.fesservice.util;

import com.ht.aems.communicate.TcpPortInfo;
import com.ht.aems.communicate.TransmitPort;
import com.ht.aems.fesmodel.CommUnit;
import com.ht.aems.fesservice.PortManager;
import com.ht.aems.fesservice.RemoteFesServer;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;


/**
 * class FCRegisterServer
 * <p> get ip information of digital terminal unit <br>
 * just for Formula company's implementation</P>
 *
 * @author Dong Shufeng
 * @version 1.0
 * @Date: 2006-3-24
 */
public class FCRegisterServer extends TransmitPort implements Runnable {

    private ServerSocket serverSocket;

    private static FCRegisterServer instance;

    private int port;

    private Map<String, String> deviceIpMap = new Hashtable<String, String>();

    private Map<String, String> nameIndex = new HashMap<String, String>();

    private FCRegisterServer() {
        port = 9688;//todo: port of tcp server
        initialIndex();
    }

    public static FCRegisterServer getInstance() {
        if (instance == null) {
            instance = new FCRegisterServer();
        }
        return instance;
    }

    private void initialIndex() {
        try {
            //read = new InputStreamReader(new FileInputStream(f),"UTF-8");
            InputStreamReader read = new InputStreamReader(this.getClass().getResourceAsStream("/hn.txt"), "Unicode");
            //read = new InputStreamReader(new FileInputStream(f),"ASCII");

            BufferedReader reader = new BufferedReader(read);
            String line;
            nameIndex.clear();
            while ((line = reader.readLine()) != null) {
                int temp = line.indexOf(" ");
                String hn = line.substring(0, temp);
                String deviceName = line.substring(temp + 1, line.length());
                nameIndex.put(hn, deviceName);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Map<String, String> getNameIndex() {
        return nameIndex;
    }

    public Map<String, String> getDeviceIpMap() {
        return deviceIpMap;
    }

    public void run() {
        while (isOpen) {
            Socket s;
            try {
                s = serverSocket.accept();
                new ServerThread(s).start();
            } catch (IOException e) {
                e.printStackTrace();
                isOpen = false;
                informErrorListeners();
                break;
            }
        }
    }

    public boolean openPort() {
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
            isOpen = false;
            return false;
        }
        Thread thread = new Thread(this);
        thread.start();
        isOpen = true;
        return true;
    }

    public void stopPort() {
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        isOpen = false;
    }

    public void stopAbnormally() {
    }

    public void send(byte[] data) {
    }

    class ServerThread extends Thread {
        private Socket s;

        ServerThread(Socket s) {
            this.s = s;
        }

        public void run() {
            byte[] readBuffer = new byte[200];
            try {
                //noinspection ResultOfMethodCallIgnored
                s.getInputStream().read(readBuffer);
                String original = new String(readBuffer);
                System.out.println(original);

                int index1, index2;
                index1 = original.indexOf("#svc");
                String name = original.substring(index1, index1 + 8);

                index2 = original.indexOf("IP");
                int index = 0;
                for (int i = index2 + 12; i <= index2 + 18; i++) {
                    char aChar;
                    aChar = original.charAt(i);
                    if (aChar == ' ') {
                        index = i;
                        break;
                    }
                }
                String ip = original.substring(index2 + 3, index);
                System.out.println(name + ":" + ip);
                String deviceName = getNameIndex().get(name);
                if (deviceName != null) {
                    deviceIpMap.put(deviceName, ip);
                    for (CommUnit r : RemoteFesServer.getInstance().getCommUnits().values()) {
                        if (r.getName().equals(deviceName)) {
                            PortManager.getInstance().removePort(r.getPortInfo());
                            ((TcpPortInfo) r.getPortInfo()).setRemoteIp(ip);
                            break;
                        }
                    }
                }
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getName(byte[] data) {
        String ipRegisterInfo = new String(data);
        int temp = ipRegisterInfo.indexOf(":");
        return ipRegisterInfo.substring(0, temp);
    }

    public static String getIp(byte[] data) {
        String ipRegisterInfo = new String(data);
        int temp = ipRegisterInfo.indexOf(":");
        return ipRegisterInfo.substring(temp + 1, ipRegisterInfo.length());
    }
}